﻿// (c) Copyright Fernando Cerqueira.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Net;
using System.Net.Mime;
using System.Text;
using System.Threading;
using System.Web;
using AppRes = WindowsPhoneCommands.Resources;

// ReSharper disable CheckNamespace
namespace WindowsPhoneCommands
// ReSharper restore CheckNamespace
{
	public static class GoogleTranslate
	{

	    public static string TranslateText(string input, string sourceLng, string translateLng, out string error)
		{
            Thread.Sleep(250); //to prevent spam detector
            var url = String.Format(EncryptDecryptMd5.DecryptString(UserSettings.Current.UrlGoogle, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef)), HttpUtility.UrlEncode(input), sourceLng, translateLng);

	        var qtdspaceend = input.Length - input.TrimEnd().Length;
            var qtdspaceini = input.Length - input.TrimStart().Length;
	        string result = null;
	        string err = null;

            try
	        {
                var proxy = UserSettings.Current.Proxy;
                var webClient = new WebClient { Encoding = Encoding.UTF8, Proxy = proxy };
                result = webClient.DownloadStringUsingResponseEncoding(url);
                var findtext = @"""" + EncryptDecryptMd5.DecryptString(UserSettings.Current.FindjsonGoogle, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef)) + @""":""";
                //find result in json formart
                var index = result.IndexOf(findtext, StringComparison.OrdinalIgnoreCase);
                if (index > 0)
                {
                    result = result.Substring(index + findtext.Length);
                    index = result.IndexOf(@""",""", StringComparison.OrdinalIgnoreCase);
                    result = result.Substring(0, index).Trim();
                    result = result + new string(' ', qtdspaceend);
                    result = result + new string(' ', qtdspaceini);
                }
                else
                {
                    err = AppRes.ErrGoogleBot;
                }
            }
	        catch (Exception ex)
	        {
	            err = ex.ToString();
	        }
	        error = err;
	        return result;
		}

		private static string DownloadStringUsingResponseEncoding(this WebClient client, string address)
		{
		    var data = client.DownloadData(address);
			var contentType = client.GetResponseContentType();
			var encoding = contentType == null || string.IsNullOrEmpty(contentType.CharSet)
						 ? client.Encoding
						 : Encoding.GetEncoding(contentType.CharSet);
			return encoding.GetString(data);
		}

		private static ContentType GetResponseContentType(this WebClient client)
		{
			var headers = client.ResponseHeaders;
			var header = headers["Content-Type"];
			return !string.IsNullOrEmpty(header)
				 ? new ContentType(header)
				 : null;
		}
	}
}
